package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 菜品管理
 */
@RestController
@RequestMapping("dish")
public class DishController {

    @Autowired
    private DishService dishService;


    /**
     * 添加菜品
     */
    @PostMapping
    @CacheEvict(cacheNames = "dish", allEntries = true)//删除所有以dish开头的缓存
    public R save(@RequestBody DishDto dishDto) {

        //保存菜品，菜品口味数据
        dishService.saveDishWithFlavor(dishDto);
        return R.success("添加成功");
    }

    /**
     * 分页查询
     */
    @GetMapping("page")
    public R<Page<DishDto>> page(Integer page, Integer pageSize, String name) {
        //传统的分页查询无法满足数据展示，因为要分类名称
        Page<DishDto> pageInfo = dishService.pageDishDto(page, pageSize, name);
        return R.success(pageInfo);
    }

    /**
     * 批量删除
     */
    @DeleteMapping
    @CacheEvict(cacheNames = "dish", allEntries = true)//删除所有以dish开头的缓存
    public R<String> deleteByIds(Long[] ids) {

        //批量删除，需要自己定义业务逻辑（菜品状态为启售的不能删除）
        dishService.deleteByIds(ids);
        return R.success("删除成功");
    }

    /**
     * 启用，停用
     */
    @PostMapping("status/{status}")
    @CacheEvict(cacheNames = "dish", allEntries = true)//删除所有以dish开头的缓存
    public R<String> updateStatus(@PathVariable Integer status, Long[] ids) {
        //批量修改状态
        // update dish set status=? where id in ( ids )
        dishService.lambdaUpdate()
                .set(Dish::getStatus, status) //修改值
                .in(Dish::getId, ids)       //条件部分
                .update();                  //更新操作
        return R.success("修改成功");
    }

    /**
     * 根据id查询菜品详情信息（包含多个口味）
     * 确定：返回一个对象 DishDto = Dish  +  List<DishFlavor>
     */
    @GetMapping("{id}")
    public R<DishDto> getById(@PathVariable Long id) {
        DishDto dishDto = dishService.getDishByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品
     */
    @PutMapping
    @CacheEvict(cacheNames = "dish", allEntries = true)//删除所有以dish开头的缓存
    public R<String> update(@RequestBody DishDto dishDto) {

        //保存菜品，菜品口味数据
        dishService.updateDishWithFlavor(dishDto);
        return R.success("修改成功");
    }


//    /**
//     * 根据条件（菜品名称，分类id）查询菜品列表
//     */
//    @GetMapping("list")
//    public R<List<Dish>> list(Long categoryId, String name) {
//        //查询数据库 select * from dish where status=1 and category_id=?
//        List<Dish> list = dishService.lambdaQuery()
//                .eq(Dish::getStatus, 1)
//                .eq(categoryId != null, Dish::getCategoryId, categoryId)
//                .like(StringUtils.isNotBlank(name), Dish::getName, name)
//                .list();
//        return R.success(list);
//    }

//    @Autowired
//    private CacheManager cacheManager;//Spring提供的各种缓存技术抽象接口。针对不同的缓存技术需要实现不同的CacheManager

    /**
     * 处理条件查询菜品信息,包含口味
     *
     * @param categoryId
     * @param name
     * @return
     */
    @GetMapping("/list")
    @Cacheable(cacheNames = "dish", key = "#categoryId + '_' +#name", unless = "#result.data.size()==0")
    public R<List<DishDto>> listDishDto(Long categoryId, String name) {
       /* String redisKey = "dish_" + categoryId + "_" + name;
        redisKey = "dish_" + DigestUtils.md5DigestAsHex(redisKey.getBytes());
        //从redis中查询数据,采用string类型
        List<DishDto> dishList = (List<DishDto>) redisTemplate.opsForValue().get(redisKey);
        //判断Redis中是否有数据
        if (dishList != null) {
            return R.success(dishList);
        }
        //说明Redis中没有数据,需要从数据库查询,并把查询的到数据存入Redis*/
        List<DishDto> list = dishService.listDishDto(categoryId, name);
//        redisTemplate.opsForValue().set(redisKey, list, 60, TimeUnit.MINUTES);
        return R.success(list);
    }
}
